package ru.megazlo.basemvc.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.megazlo.basemvc.dao.dto.Role;
import ru.megazlo.basemvc.dao.repository.UserRepository;
import ru.megazlo.basemvc.dao.dto.User;
import ru.megazlo.basemvc.service.security.AppUser;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	private UserRepository userRepository;

	@Override
	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
		User db = userRepository.findByLogin(login);
		if (db == null) {
			throw new UsernameNotFoundException("Пользователь с логином " + login + " не найден.");
		}
		AppUser rezuser = new AppUser(db.getLogin(), db.getPassword(), getAuthorities(db.getRoles()));
		rezuser.setDisplayName(db.getDisplayName());
		rezuser.setEmail(db.getEmail());
		return rezuser;
	}

	public Collection<? extends GrantedAuthority> getAuthorities(Set<Role> roles) {
		return roles.stream().map(rl -> new SimpleGrantedAuthority(rl.getName())).collect(Collectors.toList());
	}

	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}
}
